<template>
  <view class="container">
    <!-- Header -->
    <view class="header">
      <view class="header-left">
        <timer
            ref="timer"
            :auto-start="true"
            @stop="onTimerStop"
            @tick="onTimerTick"
        ></timer>
      </view>
      <view class="header-center">
        <progress-bar
            :current-step="currentQuestionIndex + 1"
            :show-info="true"
            :total-steps="questions.length"
        ></progress-bar>
      </view>
      <view class="header-right">
        <view class="score-display">
          <text class="score-text">{{ currentScore }}分</text>
        </view>
      </view>
    </view>

    <!-- Question Display -->
    <view v-if="currentQuestion" class="question-area">
      <view class="question-number">第 {{ currentQuestionIndex + 1 }} 题</view>
      <view class="question-content">
        <text class="question-text">{{ currentQuestion.question }} = ?</text>
      </view>

      <!-- Answer Input -->
      <view class="answer-input-area">
        <view class="input-container">
          <input
              v-model="userInput"
              :placeholder="inputPlaceholder"
              class="answer-input"
              @confirm="submitAnswer"
              @input="onInputChange"
          />
          <view v-if="showPercentage" class="input-suffix">%</view>
        </view>

        <!-- Quick Input Buttons -->
        <view v-if="showQuickButtons" class="quick-buttons">
          <view v-for="(row, rowIndex) in quickNumbers" :key="rowIndex" class="btn-row">
            <button
                v-for="num in row"
                :key="num"
                class="quick-btn"
                @tap="addToInput(num)"
            >
              {{ num }}
            </button>
          </view>
          <view class="btn-row btn-row-last">
            <button class="quick-btn clear-btn" @tap="clearInput">清除</button>
            <button class="quick-btn" @tap="addToInput(0)">0</button>
            <button class="quick-btn dot-btn" @tap="addToInput('.')">.</button>
          </view>
        </view>
      </view>

      <!-- Action Buttons -->
      <view class="action-buttons">
        <button
            v-if="allowSkip"
            class="action-btn skip-btn"
            @tap="skipQuestion"
        >
          <uni-icons color="#666" size="20" type="forward"></uni-icons>
          <text>跳过</text>
        </button>
        <button
            :class="{ 'disabled': !canSubmit }"
            :disabled="!canSubmit"
            class="action-btn submit-btn"
            @tap="submitAnswer"
        >
          <uni-icons color="#ffffff" size="20" type="checkmarkempty"></uni-icons>
          <text>{{ isLastQuestion ? '完成' : '下一题' }}</text>
        </button>
      </view>
    </view>

    <!-- Practice Complete -->
    <view v-if="isComplete" class="complete-overlay">
      <view class="complete-content">
        <view class="complete-icon">
          <uni-icons color="#28a745" size="60" type="checkmarkempty"></uni-icons>
        </view>
        <view class="complete-title">练习完成！</view>
        <view class="complete-stats">
          <text>答对 {{ correctCount }}/{{ questions.length }} 题</text>
        </view>
        <button class="view-result-btn" @tap="viewResult">查看结果</button>
      </view>
    </view>
  </view>
</template>

<script>
import SpeedCalcGenerator from '@/utils/question-generator/question-generator-speed-calc.js';
import CommonUtils from '@/utils/common.js';
import Timer from '@/components/common/timer.vue';
import ProgressBar from '@/components/common/progress-bar.vue';

export default {
  components: {
    Timer,
    ProgressBar
  },
  data() {
    return {
      questions: [],
      currentQuestionIndex: 0,
      userInput: '',
      startTime: 0,
      questionStartTime: 0,
      currentScore: 0,
      isComplete: false,
      settings: null,
      showQuickButtons: true,
      allowSkip: false
    }
  },
  computed: {
    currentQuestion() {
      return this.questions[this.currentQuestionIndex] || null;
    },

    isLastQuestion() {
      return this.currentQuestionIndex === this.questions.length - 1;
    },

    canSubmit() {
      return this.userInput.trim() !== '';
    },

    correctCount() {
      return this.questions.filter(q => q.isCorrect === true).length;
    },

    inputPlaceholder() {
      if (this.shouldExpectPercentageAnswer) {
        return '输入百分数值';
      }
      return '输入答案';
    },

    showPercentage() {
      return this.shouldExpectPercentageAnswer;
    },

    quickNumbers() {
      // 计算器标准布局：7-8-9, 4-5-6, 1-2-3
      return [
        [7, 8, 9],
        [4, 5, 6],
        [1, 2, 3],
      ];
    },

    // 判断是否应该期望百分数答案
    shouldExpectPercentageAnswer() {
      if (!this.currentQuestion) return false;
      // 只有当题目中包含百分数时，才可能要求用户输入百分数
      // 检查题目字符串中是否包含 '%' 符号
      return this.currentQuestion.question.includes('%');
    }
  },
  onLoad(options) {
    this.loadSettings(options);
    this.generateQuestions();
    this.startPractice();
  },
  methods: {
    // 加载设置
    loadSettings(options) {
      try {
        this.settings = JSON.parse(decodeURIComponent(options.settings));
      } catch (e) {
        console.error('Failed to parse settings:', e);
        this.settings = {
          operations: ['add', 'subtract'],
          valueTypes: ['integer'],
          count: 10
        };
      }
    },

    // 生成题目
    generateQuestions() {
      this.questions = SpeedCalcGenerator.generateQuestions({
        count: this.settings.count,
        operations: this.settings.operations,
        valueTypes: this.settings.valueTypes
      });
    },

    // 开始练习
    startPractice() {
      this.startTime = Date.now();
      this.questionStartTime = Date.now();
    },

    // 输入变化
    onInputChange(e) {
      this.userInput = e.detail.value;
    },

    // 添加到输入框
    addToInput(value) {
      if (value === '.' && this.userInput.includes('.')) {
        return; // 避免重复小数点
      }
      this.userInput += value.toString();
    },

    // 清除输入
    clearInput() {
      this.userInput = '';
    },

    // 提交答案
    submitAnswer() {
      if (!this.canSubmit) {
        uni.showToast({
          title: '请输入答案',
          icon: 'none'
        });
        return;
      }

      // 验证输入是否为有效数字
      if (!CommonUtils.isValidNumber(this.userInput)) {
        uni.showToast({
          title: '请输入有效的数字',
          icon: 'none'
        });
        return;
      }

      this.processAnswer();
    },

    // 跳过题目
    skipQuestion() {
      this.currentQuestion.userAnswer = null;
      this.currentQuestion.isCorrect = false;
      this.currentQuestion.timeUsed = (Date.now() - this.questionStartTime) / 1000;

      this.nextQuestion();
    },

    // 处理答案
    processAnswer() {
      let userAnswer = parseFloat(this.userInput);
      const correctAnswer = this.currentQuestion.answer;

      // 如果题目中包含百分数且用户输入的是百分数，则转换为小数
      if (this.shouldExpectPercentageAnswer && !isNaN(userAnswer)) {
        userAnswer = userAnswer / 100; // 将百分数转换为小数
      }

      // 使用容错率判断方法校验答案是否正确
      const isCorrect = SpeedCalcGenerator.isAnswerCorrectWithTolerance(userAnswer, correctAnswer);

      this.currentQuestion.userAnswer = userAnswer;
      this.currentQuestion.isCorrect = isCorrect;
      this.currentQuestion.timeUsed = (Date.now() - this.questionStartTime) / 1000;

      // 显示反馈
      this.showAnswerFeedback(isCorrect);

      // 更新分数
      if (isCorrect) {
        this.currentScore += 10; // 每题10分基础分
      }

      // 延迟进入下一题
      setTimeout(() => {
        this.nextQuestion();
      }, 1000);
    },

    // 显示答案反馈
    showAnswerFeedback(isCorrect) {
      let answerDisplay = this.currentQuestion.answer;

      // 如果题目中包含百分数，则以百分数形式显示答案
      if (this.shouldExpectPercentageAnswer) {
        answerDisplay = `${(this.currentQuestion.answer * 100).toFixed(2).replace(/\.?0+$/, '')}%`;
      }

      uni.showToast({
        title: isCorrect ? `答对了！正确答案是 ${answerDisplay}` : `错误，正确答案是 ${answerDisplay}`,
        icon: isCorrect ? 'success' : 'none',
        duration: 1000
      });
    },

    // 下一题
    nextQuestion() {
      if (this.isLastQuestion) {
        this.completePractice();
      } else {
        this.currentQuestionIndex++;
        this.userInput = '';
        this.questionStartTime = Date.now();
      }
    },

    // 完成练习
    completePractice() {
      this.$refs.timer.stop();
      this.isComplete = true;

      // 延迟2秒后自动跳转到结果页面
      setTimeout(() => {
        this.viewResult();
      }, 2000);
    },

    // 查看结果
    viewResult() {
      const totalTime = (Date.now() - this.startTime) / 1000;
      const resultData = {
        questions: this.questions,
        totalTime,
        settings: this.settings,
        startTime: this.startTime,
        endTime: Date.now()
      };

      uni.navigateTo({
        url: '/pages/speed-calc/result',
        success: () => {
          getApp().globalData.speedCalcResult = resultData;
        }
      });
    },

    // 计时器事件
    onTimerTick(time) {
      // 可以在这里添加时间相关的逻辑
    },

    onTimerStop(time) {
      // 计时器停止
    }
  },
  onUnload() {
    // 页面卸载时停止计时器
    if (this.$refs.timer) {
      this.$refs.timer.stop();
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  height: 100vh;
  background: linear-gradient(135deg, #a8f3f0 0%, #7dd3fc 100%);
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10rpx);

  .header-left,
  .header-right {
    flex: 0 0 140rpx;
  }

  .header-center {
    flex: 1;
    margin: 0 20rpx;
  }

  .score-display {
    text-align: right;

    .score-text {
      color: white;
      font-weight: bold;
      font-size: 28rpx;
    }
  }
}

.question-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 60rpx 40rpx;
  color: white;
}

.question-number {
  text-align: center;
  font-size: 28rpx;
  opacity: 0.8;
  margin-bottom: 30rpx;
}

.question-content {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 60rpx;

  .question-text {
    font-size: 48rpx;
    font-weight: bold;
    text-align: center;
    line-height: 1.2;
  }
}

.answer-input-area {
  margin-bottom: 60rpx;

  .input-container {
    position: relative;
    margin-bottom: 40rpx;

    .answer-input {
      width: 100%;
      height: 100rpx;
      background: rgba(255, 255, 255, 0.9);
      border: none;
      border-radius: 15rpx;
      text-align: center;
      font-size: 40rpx;
      font-weight: bold;
      color: #333;

      &::placeholder {
        color: #999;
        font-size: 32rpx;
        font-weight: normal;
      }
    }

    .input-suffix {
      position: absolute;
      right: 30rpx;
      top: 50%;
      transform: translateY(-50%);
      font-size: 36rpx;
      font-weight: bold;
      color: #666;
    }
  }

  .quick-buttons {
    display: flex;
    flex-direction: column;
    gap: 20rpx;

    .btn-row {
      display: flex;
      gap: 20rpx;
      justify-content: center;

      .quick-btn {
        flex: 1;
        max-width: 140rpx;
        height: 100rpx;
        background: rgba(255, 255, 255, 0.25);
        border: 2rpx solid rgba(255, 255, 255, 0.4);
        border-radius: 15rpx;
        color: white;
        font-size: 36rpx;
        font-weight: bold;
        display: flex;
        align-items: center;
        justify-content: center;
        box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
        transition: all 0.2s;

        &.clear-btn {
          background: rgba(239, 68, 68, 0.3);
          border-color: rgba(239, 68, 68, 0.5);
          font-size: 28rpx;
        }

        &.dot-btn {
          font-size: 48rpx;
        }

        &:active {
          background: rgba(255, 255, 255, 0.4);
          transform: scale(0.95);
          box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.15);
        }

        &.clear-btn:active {
          background: rgba(239, 68, 68, 0.5);
        }
      }
    }
  }
}

.action-buttons {
  display: flex;
  gap: 20rpx;

  .action-btn {
    flex: 1;
    height: 80rpx;
    border: none;
    border-radius: 15rpx;
    font-size: 30rpx;
    font-weight: bold;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10rpx;

    &.skip-btn {
      background: rgba(255, 255, 255, 0.2);
      color: white;
      border: 2rpx solid rgba(255, 255, 255, 0.3);
    }

    &.submit-btn {
      background: linear-gradient(135deg, #28a745, #20c997);
      color: white;

      &.disabled {
        background: rgba(108, 117, 125, 0.5);
        opacity: 0.6;
      }
    }

    &:active:not(.disabled) {
      transform: scale(0.98);
    }
  }
}

.complete-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;

  .complete-content {
    background: white;
    padding: 80rpx 60rpx;
    border-radius: 20rpx;
    text-align: center;
    margin: 0 60rpx;

    .complete-icon {
      margin-bottom: 30rpx;
    }

    .complete-title {
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 20rpx;
    }

    .complete-stats {
      font-size: 28rpx;
      color: #666;
      margin-bottom: 40rpx;
    }

    .view-result-btn {
      width: 100%;
      height: 80rpx;
      background: linear-gradient(135deg, #67e8f9, #38bdf8);
      border: none;
      border-radius: 10rpx;
      color: white;
      font-size: 30rpx;
      font-weight: bold;
    }
  }
}
</style>